/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package interfaz;

import clases.ClsDatabase;
import clases.ClsMetodos;
import clases.ClsSesion;
import javax.swing.ImageIcon;

public class frmAcceso extends javax.swing.JFrame {

    private ClsDatabase bd = new ClsDatabase();
//    private ClsSeguridad seguridad = new ClsSeguridad();
    private ClsSesion sesion = new ClsSesion();
    private ClsMetodos metodos = new ClsMetodos();
    private int intentos = 1;

    /**
     * Creates new form frmAcceso1
     */
    public frmAcceso() {
        initComponents();
        setIconImage(new ImageIcon(getClass().getResource("/resource/icon/principales/Logo.png")).getImage());
//        this.txtUsuario.setText("");
//        this.pswPassword.setText("");
        this.txtUsuario.requestFocus();
        //Configuramos la clase bd
//        bd.setDataBase("bd_prueba2");
//        bd.setUser("root");
//        bd.setPassword("admin");
        this.setLocationRelativeTo(null);
        lblMensaje.setVisible(false);
    }

    //___________________________________________________________________________________ Soy una barra separadora :)
    /**
     * @descripcion Se ejecuta cuando se realiza click sobre el boton Aceptar de
     * la interfaz
     */
    public void _aceptar() {
        if (intentos < 4) {
            //Obtenemos los valores de los jtextfield
            String userString = this.txtUsuario.getText().toString();
            String passString = this.pswPassword.getText().toString();
            //Encriptamos el passString a MD5
            //passString = seguridad.encriptar(passString, seguridad.getMD5());

            //Verificamos en la BD el acceso de usuario
            Object[][] datos = bd.select("usuario", "nombre_usuario,idusuario,idusuario_tipo,nombre", "nombre_usuario='" + userString + "' and password='" + passString + "'");
            if (datos != null) {
                ClsSesion.iduser = datos[0][1].toString();//Guardamos el id del User
                ClsSesion.nombre_usuario = datos[0][3].toString();
                ClsSesion.idtipoUsuario = datos[0][2].toString();
                System.out.println("dato:" + datos[0][0].toString());
                System.out.println("id:" + ClsSesion.iduser);
                sesion._getPermisosTabla(ClsSesion.iduser, userString, ClsSesion.idtipoUsuario, bd);
                System.out.println("...");
//                accesoSistema = true;
                //            frmPrincipal frame = new frmPrincipal(bd);
                frmPrincipal frame = new frmPrincipal();
                this.dispose();
                frame.setVisible(true);
            } else {
                //lblTitulo.setBackground(colorError);
                // pnlContenedorPrincipal.setBackground(colorError);
                lblMensaje.setText("Escriba correctamente sus datos");
                lblMensaje.setVisible(true);
                pswPassword.setText("");
                intentos++;
            }
        } else {
            metodos._cerrarSistema();
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        btnAceptar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        txtUsuario = new javax.swing.JTextField();
        pswPassword = new javax.swing.JPasswordField();
        lblMensaje = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Acceso al sistema");
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("Usuario");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 70, -1, -1));

        btnAceptar.setText("Aceptar");
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });
        getContentPane().add(btnAceptar, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 170, 120, 30));

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });
        getContentPane().add(btnCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(230, 170, 130, 30));

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setText("Contraseña");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 120, -1, -1));

        txtUsuario.setText("admin");
        txtUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtUsuarioKeyTyped(evt);
            }
        });
        getContentPane().add(txtUsuario, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 90, 270, -1));

        pswPassword.setText("123");
        pswPassword.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                pswPasswordKeyTyped(evt);
            }
        });
        getContentPane().add(pswPassword, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 140, 270, -1));

        lblMensaje.setFont(new java.awt.Font("Tahoma", 0, 9)); // NOI18N
        lblMensaje.setForeground(new java.awt.Color(102, 102, 102));
        lblMensaje.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/error.gif"))); // NOI18N
        lblMensaje.setText("mensaje");
        getContentPane().add(lblMensaje, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 210, -1, -1));

        jLabel4.setText("<html>Por favor ingrese su usuario y contraseña  para acceder al Sistema de costos de saneamiento básico.</html>");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 10, 280, 60));

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resource/icon/principales/fondo_acceso.jpg"))); // NOI18N
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, 240));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        _aceptar();
    }//GEN-LAST:event_btnAceptarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        System.exit(0);
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void pswPasswordKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_pswPasswordKeyTyped
        if (evt.getKeyChar() == 10) {
            _aceptar();

        }
    }//GEN-LAST:event_pswPasswordKeyTyped

    private void txtUsuarioKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUsuarioKeyTyped
        if (evt.getKeyChar() == 10) {
            pswPassword.requestFocus();

        }
    }//GEN-LAST:event_txtUsuarioKeyTyped

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(frmAcceso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(frmAcceso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(frmAcceso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(frmAcceso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new frmAcceso().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAceptar;
    private javax.swing.JButton btnCancelar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel lblMensaje;
    private javax.swing.JPasswordField pswPassword;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables
}
